package com.signin.controller;

import com.signin.service.SignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/sign-in/export")
public class ExportController {

    @Autowired
    private SignInService signInService;

    // 导出签到数据
    @GetMapping("/{id}")
    public ResponseEntity<?> exportSignInData(@PathVariable("id") Long sessionId) {
        try {
            byte[] data = signInService.exportSignInData(sessionId);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "sign_in_records.xlsx");
            headers.setContentLength(data.length);
            
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("导出失败: " + e.getMessage());
        }
    }
    
    // 导出历史签到数据
    @GetMapping("/history")
    public ResponseEntity<?> exportHistoricalData(
            @RequestParam(value = "classroom", required = false) String classroom,
            @RequestParam(value = "startDate", required = false) Long startDate,
            @RequestParam(value = "endDate", required = false) Long endDate) {
        // 构建参数Map
        Map<String, Object> params = new HashMap<>();
        params.put("classroom", classroom);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        try {
            byte[] data = signInService.exportHistoricalData(params);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "historical_sign_in_records.xlsx");
            headers.setContentLength(data.length);
            
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("导出失败: " + e.getMessage());
        }
    }
}